{#
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
#}

{% extends "airflow/dag.html" %}

{% block page_title %}{{ dag.dag_id }} - Graph - Airflow{% endblock %}

{% block head_css %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/graph.css') }}">
<style type="text/css">
  {% for state, state_color in state_color_mapping.items() %}
    g.node.{{state}} rect {
      stroke: {{state_color}};
    }
  {% endfor %}
</style>
{% endblock %}

{% block content %}
{{ super() }}
{% if doc_md %}
{{ doc_md }}
{% endif %}
<div class="form-inline">
  <form method="get" style="float:left;">
    {{ state_token }}
    Base date: {{ form.base_date(class_="form-control") }}
    Number of runs: {{ form.num_runs(class_="form-control") }}
    Run:
    {{ form.execution_date(class_="form-control") }}
    Layout:
    {{ form.arrange(class_="form-control") }}
    <input type="hidden" name="root" value="{{ root }}">
    <input type="hidden" value="{{ dag.dag_id }}" name="dag_id">
    <input name="_csrf_token" type="hidden" value="{{ csrf_token() }}">
    <input type="submit" value="Go" class="btn btn-default">
  </form>
  <div class="input-group" style="float: right;">
    <input type="text" id="searchbox" class="form-control" placeholder="Search for...">
  </div>
  <div style="clear: both;"></div>
</div>
<hr/>
<div>
  {% for op in operators %}
  <div class="legend_item"
       style="border-width:1px;float:left;background:{{ op.ui_color }};color:{{ op.ui_fgcolor }};">
    {{ op.task_type }}
  </div>
  {% endfor %}

  <div>
    <div class="legend_item state" style="border-color:white;">no_status</div>
  {% for state, state_color in state_color_mapping.items() %}
    <div class="legend_item state" style="border-color:{{state_color}};">{{state}}</div>
  {% endfor %}
  </div>
  <div style="clear:both;"></div>
</div>
<div id="error" style="display: none; margin-top: 10px;" class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span id="error_msg">Oops.</span>
</div>
<hr style="margin-bottom:0;"/>
<button class="btn btn-default pull-right" id="refresh_button">
  <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
</button>
<div id="svg_container">

  <svg width="{{ width }}" height="{{ height }}">
    <g id='dig' transform="translate(20,20)"></g>
    <filter id="blur-effect-1">
      <feGaussianBlur stdDeviation="3"></feGaussianBlur>
    </filter>
  </svg>
  <img id="loading" alt="spinner" src="{{ url_for('static', filename='loading.gif') }}">
</div>
<hr>
{% endblock %}

{% block tail %}
{{ super() }}

<script src="{{ url_for_asset('d3.min.js') }}"></script>
<script src="{{ url_for_asset('dagre-d3.min.js') }}"></script>
<script src="{{ url_for_asset('d3-tip.js') }}"></script>
<script>

    var highlight_color = "#000000";
    var upstream_color = "#2020A0";
    var downstream_color = "#0000FF";
    var initialStrokeWidth = '3px';
    var highlightStrokeWidth = '5px';

    var nodes = {{ nodes|tojson }};
    var edges = {{ edges|tojson }};
    var execution_date = "{{ execution_date }}";
    var arrange = "{{ arrange }}";

    // Below variables are being used in dag.js
    var tasks = {{ tasks|tojson }};
    var task_instances = {{ task_instances|tojson }};
    var getTaskInstanceURL = "{{ url_for('Airflow.task_instances') }}" +
      "?dag_id=" + encodeURIComponent(dag_id) + "&execution_date=" +
      encodeURIComponent(execution_date);

    var duration = 500;
    var stateFocusMap = {
        'success': false,
        'running':false,
        'failed':false,
        'skipped': false,
        'upstream_failed': false,
        'up_for_reschedule': false,
        'up_for_retry': false,
        'queued': false,
        'no_status': false
    };
    const taskTip = d3.tip()
      .attr('class', 'tooltip d3-tip')
      .html(function(toolTipHtml) {
        return toolTipHtml;
      });

    // Preparation of DagreD3 data structures
    var g = new dagreD3.graphlib.Graph().setGraph({
        nodesep: 15,
        ranksep: 15,
        rankdir: arrange,
      })
      .setDefaultEdgeLabel(function() { return { lineInterpolate: 'basis' } });

    // Set all nodes and styles
    nodes.forEach(function(node) {
      g.setNode(node.id, node.value)
    });

    // Set edges
    edges.forEach(function(edge) {
      g.setEdge(edge.source_id, edge.target_id);
    });

    var render = dagreD3.render(),
      svg = d3.select("svg"),
      innerSvg = d3.select("svg g");

    innerSvg.call(render, g);
    innerSvg.call(taskTip);

    function setUpZoomSupport() {
      // Set up zoom support for Graph
      var zoom = d3.behavior.zoom().on("zoom", function() {
            innerSvg.attr("transform", "translate(" + d3.event.translate + ")" +
                                        "scale(" + d3.event.scale + ")");
          });
      svg.call(zoom);

      // Centering the DAG on load
      // Get Dagre Graph dimensions
      var graphWidth = g.graph().width;
      var graphHeight = g.graph().height;
      // Get SVG dimensions
      var padding = 20;
      var svgBb = svg.node().getBoundingClientRect();
      var width = svgBb.width - padding*2;
      var height = svgBb.height - padding;  // we are not centering the dag vertically

      // Calculate applicable scale for zoom
      zoomScale = Math.min(
        Math.min(width / graphWidth, height / graphHeight),
        1.5,  // cap zoom level to 1.5 so nodes are not too large
      );

      zoom.translate([(width/2) - ((graphWidth*zoomScale)/2) + padding, padding]);
      zoom.scale(zoomScale);
      zoom.event(innerSvg);
    }

    setUpZoomSupport();
    inject_node_ids(tasks);

    d3.selectAll("g.node").on("click", function(d){
        task = tasks[d];
        if (d in task_instances)
            try_number = task_instances[d].try_number;
        else
            try_number = 0;

        if (task.task_type == "SubDagOperator")
            call_modal(d, execution_date, task.extra_links, try_number, true);
        else
            call_modal(d, execution_date, task.extra_links, try_number, undefined);
    });


    function highlight_nodes(nodes, color, stroke_width) {
        nodes.forEach (function (nodeid) {
            my_node = d3.select('[id="' + nodeid + '"]').node().parentNode;
            d3.select(my_node)
                .selectAll("rect")
                .style("stroke", color)
                .style("stroke-width", stroke_width) ;
        })
    }

    d3.selectAll("g.node").on("mouseover", function(d){
        d3.select(this).selectAll("rect").style("stroke", highlight_color) ;
        highlight_nodes(g.predecessors(d), upstream_color, highlightStrokeWidth);
        highlight_nodes(g.successors(d), downstream_color, highlightStrokeWidth)
        adjacent_node_names = [d, ...g.predecessors(d), ...g.successors(d)]
        d3.selectAll("g.nodes g.node")
            .filter(x => !adjacent_node_names.includes(x))
            .style("opacity", 0.2);
        adjacent_edges = g.nodeEdges(d)
        d3.selectAll("g.edgePath")[0]
            .filter(x => !adjacent_edges.includes(x.__data__))
            .forEach(function(x) {
                d3.select(x).style('opacity', .2)
            })
    });

    d3.selectAll("g.node").on("mouseout", function(d){
        d3.select(this).selectAll("rect").style("stroke", null) ;
        highlight_nodes(g.predecessors(d), null, initialStrokeWidth)
        highlight_nodes(g.successors(d), null, initialStrokeWidth)
        d3.selectAll("g.node")
            .style("opacity", 1);
        d3.selectAll("g.node rect")
            .style("stroke-width", initialStrokeWidth);
        d3.selectAll("g.edgePath")
            .style("opacity", 1);
    });


    {% if blur %}
    d3.selectAll("text").attr("class", "blur");
    {% endif %}

    d3.selectAll("div.legend_item.state")
        .style("cursor", "pointer")
        .on("mouseover", function(){
            if(!stateIsSet()){
                state = d3.select(this).text();
                focusState(state);
            }
        })
        .on("mouseout", function(){
            if(!stateIsSet()){
                clearFocus();
            }
        });

    d3.selectAll("div.legend_item.state")
        .on("click", function(){
            state = d3.select(this).text();
            color = d3.select(this).style("border-color");

            if (!stateFocusMap[state]){
                clearFocus();
                focusState(state, this, color);
                setFocusMap(state);

            } else {
                clearFocus();
                setFocusMap();
            }
        });

    d3.select("#searchbox").on("keyup", function(){
        var s = document.getElementById("searchbox").value;
        var match = null;

        if (stateIsSet){
            clearFocus();
            setFocusMap();
        }

        d3.selectAll("g.nodes g.node").filter(function(d, i){
            if (s==""){
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 1);
                d3.select(this)
                    .transition().duration(duration)
                    .style("opacity", 1)
                    .selectAll("rect")
                    .style("stroke-width", initialStrokeWidth);
            }
            else{
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 0.2);
                if (d.indexOf(s) > -1) {
                    if (!match)
                        match = this;
                    d3.select(this)
                        .transition().duration(duration)
                        .style("opacity", 1)
                        .selectAll("rect")
                        .style("stroke-width", highlightStrokeWidth);
                }
                else {
                    d3.select(this)
                        .transition()
                        .style("opacity", 0.2).duration(duration)
                        .selectAll("rect")
                        .style("stroke-width", initialStrokeWidth);
                }
            }
        });

        // This moves the matched node in the center of the graph area
        // ToDo: Should we keep this here as it has no added value
        // and does not fit the graph on small screens, and has to scroll
        if(match) {
            var transform = d3.transform(d3.select(match).attr("transform"));
            transform.translate = [
                -transform.translate[0] + 520,
                -(transform.translate[1] - 400)
            ];
            transform.scale = [1, 1];

            d3.select("g.zoom")
                .transition()
                .attr("transform", transform.toString());
            innerSvg.attr("transform", "translate(" + transform.translate + ")" +
                                        "scale(1)");
        }
    });


    // Injecting ids to be used for parent/child highlighting
    // Separated from updateNodeStates since it must work even
    // when there is no valid task instance available
    function inject_node_ids(tasks) {
        $.each(tasks, function(task_id, task) {
            $('tspan').filter(function(index) { return $(this).text() === task_id; })
                    .parent().parent().parent()
                    .attr("id", task_id);
        });
    }

    function clearFocus(){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node rect")
            .transition(duration)
            .style("stroke-width", initialStrokeWidth);
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 1);
        d3.selectAll("div.legend_item.state")
            .style("background-color", null);
    }

    function focusState(state, node, color){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 0.2);
        d3.selectAll("g.node."+state)
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node." + state + " rect")
            .transition(duration)
            .style("stroke-width", highlightStrokeWidth)
            .style("opacity", 1);
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 0.2);
        d3.select(node)
            .style("background-color", color);
    }

    function setFocusMap(state){
        for (var key in stateFocusMap){
                stateFocusMap[key] = false;
        }
        if(state != null){
            stateFocusMap[state] = true;
        }
    }

    function stateIsSet(){
        for (var key in stateFocusMap){
            if (stateFocusMap[key]){
                return true
            }
        }
        return false
    }

    function initRefreshButton() {
      d3.select("#refresh_button").on("click", () => {
        $("#loading").css("display", "block");
        $("div#svg_container").css("opacity", "0.2");
        $.get(getTaskInstanceURL)
          .done(
            (task_instances) => {
              updateNodesStates(JSON.parse(task_instances));
              $("#loading").hide();
              $("div#svg_container").css("opacity", "1");
              $('#error').hide();
            }
          ).fail((_, textStatus, err) => {
            $('#error_msg').html(`${textStatus}: ${err}`);
            $('#error').show();
            $('#loading').hide();
            $('#chart_section').hide(1000);
            $('#datatable_section').hide(1000);
          });
      });
    }

    // Assigning css classes based on state to nodes
    // Initiating the tooltips
    function updateNodesStates(task_instances) {
      $.each(task_instances, (task_id, ti) => {
        $('tspan').filter((index, el) => {
          return $(el).text() === task_id;
        })
          .parent().parent().parent().parent()
          .attr("class", "node enter " + (ti.state ? ti.state : "no_status"))
          .attr("data-toggle", "tooltip")
          .on("mouseover", (evt) => {
            const task = tasks[task_id];
            const tt = tiTooltip(ti);
            taskTip.show(tt, evt.target); // taskTip is defined in graph.html
          })
          .on('mouseout', taskTip.hide);
      });
    }

    updateNodesStates(task_instances);
    initRefreshButton();

</script>
<script src="{{ url_for_asset('graph.js') }}"></script>
<script src="{{ url_for_asset('task-instances.js') }}"></script>


{% endblock %}
